package org.chen.utils;


import org.chen.response.Page;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;

import java.util.Collections;
import java.util.List;

// 修改 PageHelper
public class PageHelper {
    public static <T> Page<T> getPage(Query query, Class<T> clazz,
                                      Integer pageNum, Integer pageSize,
                                      MongoTemplate mongoTemplate) {
        // 获取总数
        long total = mongoTemplate.count(query, clazz);

        // 分页
        pageNum = pageNum == null || pageNum < 1 ? 1 : pageNum;
        pageSize = pageSize == null || pageSize < 1 ? 10 : pageSize;

        query.skip((long) (pageNum - 1) * pageSize).limit(pageSize);

        List<T> content = mongoTemplate.find(query, clazz);

        return Page.of(content, total, pageSize, pageNum);
    }

    // 添加一个方法用于处理已有列表的分页
    public static <T> Page<T> getPage(List<T> list, int pageNum, int pageSize) {
        if (list == null || list.isEmpty()) {
            return Page.of(Collections.emptyList(), 0, pageSize, pageNum);
        }

        int total = list.size();
        int fromIndex = (pageNum - 1) * pageSize;
        int toIndex = Math.min(fromIndex + pageSize, total);

        if (fromIndex >= total) {
            return Page.of(Collections.emptyList(), total, pageSize, pageNum);
        }

        return Page.of(list.subList(fromIndex, toIndex), total, pageSize, pageNum);
    }
}
